from flask import Flask, jsonify, request
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)
CORS(app)

# 配置数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(os.path.dirname(__file__), 'data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# 导入模型
from models import Customer, Order, Product, Inquiry

# 测试接口
@app.route('/api/test', methods=['GET'])
def test_api():
    return jsonify({"message": "Backend is running!"})

# 客户管理模块
@app.route('/api/customers', methods=['GET', 'POST'])
def handle_customers():
    if request.method == 'GET':
        customers = Customer.query.all()
        return jsonify([{"id": c.id, "company_name": c.company_name, "contact_name": c.contact_name} for c in customers])
    elif request.method == 'POST':
        data = request.get_json()
        new_customer = Customer(company_name=data['company_name'], contact_name=data['contact_name'])
        db.session.add(new_customer)
        db.session.commit()
        return jsonify({"message": "Customer added successfully"}), 201

# 订单管理模块
@app.route('/api/orders', methods=['GET', 'POST'])
def handle_orders():
    if request.method == 'GET':
        orders = Order.query.all()
        return jsonify([{"id": o.id, "status": o.status, "customer_id": o.customer_id} for o in orders])
    elif request.method == 'POST':
        data = request.get_json()
        new_order = Order(status=data['status'], customer_id=data['customer_id'])
        db.session.add(new_order)
        db.session.commit()
        return jsonify({"message": "Order added successfully"}), 201

# 产品管理模块
@app.route('/api/products', methods=['GET', 'POST'])
def handle_products():
    if request.method == 'GET':
        products = Product.query.all()
        return jsonify([{"id": p.id, "name": p.name, "price": p.price} for p in products])
    elif request.method == 'POST':
        data = request.get_json()
        new_product = Product(name=data['name'], price=data['price'])
        db.session.add(new_product)
        db.session.commit()
        return jsonify({"message": "Product added successfully"}), 201

# 询盘管理模块
@app.route('/api/inquiries', methods=['GET', 'POST'])
def handle_inquiries():
    if request.method == 'GET':
        inquiries = Inquiry.query.all()
        return jsonify([{"id": i.id, "status": i.status, "assigned_to": i.assigned_to} for i in inquiries])
    elif request.method == 'POST':
        data = request.get_json()
        new_inquiry = Inquiry(status=data['status'], assigned_to=data['assigned_to'])
        db.session.add(new_inquiry)
        db.session.commit()
        return jsonify({"message": "Inquiry added successfully"}), 201

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)